<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use App\Models\App;

class Attach extends Model
{
	protected $app;
	protected $table = 'attaches';
	protected $fillable=['app_id','app_name','file','ext','note','user_id','buys','downloads'];

	public $casts = [];  //设置字段格式 

    protected $fileTypes = [
        'image'  => '/^(gif|png|jpe?g|svg|bmp)$/i',
        'video'  => '/^(og?|mp4|webm|mp?g|mov|3gp)$/i',
        'audio'  => '/^(og?|mp3|wav|mid|midi)$/i',
		'office'  => '/^(csv|doc|docx|xls|xlsx|ppt)$/i',
		'zip'    => '/^(zip|rar|7z|jar|tar|gz)$/i',
    ];

	//protected $appends = ['type'];


    public function __construct($app_name='')
    {        
		if( $app_name ){
			static::addGlobalScope('avaiable',function (Builder $builder){
				$builder->where('app_name',$app_name);
			});
		}
    }


    public function setfileAttribute($value)
    {
        if(!empty($value)){
			$this->attributes['ext'] = get_file_type($value);
			$this->attributes['file'] = $value;
		}
    }

    /**
     * @return string
    */ 
    protected function getFileType($file)
    {     
		$filetype = '';
		$farr =  array_filter(str2arr($file,'/'));
		$file = end($farr);
		$arr = str2arr($file,'.');
		if(count($arr) >1 && !empty(end($arr))){
			$ext = end($arr);
			foreach ($this->fileTypes as $type => $pattern) {
				if (preg_match($pattern, $ext) === 1) {
					$filetype = $type;
					break;
				}
			}
			if($filetype) $filetype=$ext; //未找到类型直接返回扩展名.
		}
        return $filetype;
    }

}
